const {slugify} = require('transliteration');
const Base = require('./base.js');
// const md5 = require("md5");

module.exports = class extends Base {

    async _initialize() {
        await super._initialize();
    }

    async indexAction() {

        let Model = this.mongoose('Config');
        //'CONFIG_GROUP_LIST'
        let data = await Model.findOne({key: `CONFIG_GROUP_LIST`}).exec();

        // console.log(data);

        let groups = [];
        if (data && data['value']) {
            for (let item of data['value'].split('|')) {
                let pairs = item.split(':');
                groups.push({key: Number(pairs[0]), title: pairs[1]});
            }
        }

        this.assign({
            status: [{key: '0', title: '关闭'}, {key: '1', title: '开启'}],
            groups: groups
        });
        await this.display('admin/config/index');
    }

    async tableAction() {

        const p = this.query('page') || 1;

        const id = this.post('id');
        const status = this.post('status');
        const keywords = this.post('keywords');
        const group = this.post('group');

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (keywords !== "") {
            queryParams = {
                $or: [
                    {key: {$regex: keywords, $options: "$i"}},
                    {title: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (status !== "") {
            queryParams = Object.assign(queryParams, {status: status});
        }

        if (group !== "") {
            queryParams = Object.assign(queryParams, {group: Number(group)});
        }

        //id属性要单独查找,不支持正则表达式
        if (id !== "") {
            try {
                queryParams = {
                    _id: think.Mongoose.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.error(1001, '没找到符合条件的记录');
                return;
            }
        }

        const Model = this.mongoose('Config');
        let pageSize = await Model.C('LIST_ROWS');

        const pageEntity = await Model.findPage( {
            page: p,
            pageSize: pageSize
        }, '', queryParams, {}, {group: 'desc'});

        this.assign({
            records: pageEntity.data,
            pager: super.ajaxPage(p, pageEntity.pagination.rowCount, pageEntity.pagination.pageSize)
        });
        await this.display('admin/config/table');
    }

    async disableAction() {
        const id = this.post('id') || "";
        const ids = id.split(',');
        const Model = this.mongoose('Config');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 0}).exec();
        }
        this.success('', '禁用成功');
    }

    async enableAction() {
        const id = this.post('id') || "";
        const ids = id.split(',');
        let Model = this.mongoose('Config');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 1}).exec();
            // this.changeModelField('admin/Config', i, 'status', 1);
        }
        this.success('', '开启成功');
    }

    async deleteAction() {
        const id = this.post('id') || "";
        const ids = id.split(',');
        const Model = this.mongoose('Config');
        for (const i of ids) {
            await Model.findByIdAndRemove(i).exec();
        }
        this.success('/admin/admin/index', '删除成功');
    }

    async addAction() {

        if (this.isPost) {

            if (think.isEmpty(this.post('key'))) {
                this.error(1001, '参数错误');
            }

            const data = {
                key: this.post('key'),
                value: this.post('value'),
                title: this.post('title'),
                sort: this.post('sort'),
                valueType: this.post('valueType'),
                group: this.post('group'),
                extra: this.post('extra'),
                remark: this.post('remark')
            };

            const Model = this.mongoose('Config');
            if (!think.isEmpty(this.post('id'))) {
                await Model.findByIdAndUpdate(this.post('id'), data).exec();
                this.success('/admin/config/index', '配置项更新成功');
            } else {
                await Model.create(data);
                this.success('/admin/config/index', '创建新配置项成功');
            }

        } else {
            //Edit
            const Model = this.mongoose('Config');
            const data = await Model.findOne({key: `CONFIG_GROUP_LIST`}).exec();
            let groups = [];
            for (const item of data['value'].split('|')) {
                const pairs = item.split(':');
                groups.push({key: Number(pairs[0]), title: pairs[1]});
            }

            const valueTypes = [
                {key: 'Number', title: '数字'},
                {key: 'String', title: '字符串'},
                {key: 'Text', title: '文本'},
                {key: 'Array', title: '数组'},
                {key: 'MultiCheckList', title: '多选框'}
            ];

            const options = {
                groups: groups,
                valueTypes: valueTypes
            };

            if (this.query('id')) {
                const config = await Model.findOne({_id: this.query('id')}).lean().exec();
                this.assign(Object.assign(options, {config: config}));
                await this.display('admin/config/add');
            } else {
                //add new item
                this.assign(options);
                await this.display('admin/config/add');
            }
        }
    }
}